<template>
  <!-- 品牌关联 对话框-->
  <el-dialog
    title="品牌关联"
    :visible.sync="isBrandDialogVisible"
    width="600px"
    append-to-body
    @close="onCloseBrandDialog"
  >

    <el-row>
      <el-col>
        <el-tag
          size="medium"
          :key="brand.id"
          v-for="brand in brandList"
          closable
          :disable-transitions="false"
          @close="onRemoveTag(brand)">
          {{ brand.name }}
        </el-tag>

        <el-autocomplete
          ref="saveTagInput"
          class="input-new-tag"
          v-if="inputVisible"
          v-model="queryString"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入品牌"
          @select="handleSelect"
          size="mini"
        ></el-autocomplete>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Brand</el-button>
      </el-col>
    </el-row>

    <span slot="footer" class="dialog-footer">
          <el-button @click="isBrandDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handlingAssociatedBrands">确 定</el-button>
      </span>
  </el-dialog>
</template>

<script>

import {getBrand, getBrandsByName, updateBrand} from "@/api/prod/category";

export default {
  name: "brandAssociation",
  props: {
    categoryId: {
      type: Number,
      default: null
    }

  },
  data(){
    return {
      //控制品牌对话框是否隐藏和显示
      isBrandDialogVisible: false,


      inputVisible: false,
      inputValue: '',

      queryString: '',
      timeout: null,

      queryData: {
        pageNum: 1,
        pageSize: 50,
        name: "",
        status: 1
      },

      brandIds: [],
      brandList: []
    }
  },
  methods: {

    show() {
      this.$nextTick(
        function (){
          if (this.categoryId){
            this.getBrandData()
          }else {
            this.$modal.msgWarning("请先选择三级类目!");
          }
        }
      )
    },
    getBrandData(){
      getBrand(this.categoryId).then(response => {
        // console.log(this.categoryId)
        // // 方法1
        // let brands = response.data
        // for (const brandsKey in brands) {
        //   let brand = brands[brandsKey];
        //   let tag = {};
        //   tag.id = brand.brandId;
        //   tag.name = brand.brandName;
        //   this.brandList.push(tag);
        //   this.isBrandDialogVisible = true;
        // }

        // 方法2
        this.brandList = response.data.map(item => {
          return {
            id: item.brandId,
            name: item.brandName
          }
        })
        this.isBrandDialogVisible = true;
        // console.log(this.brandList)
      })
    },
    onRemoveTag(brand) {
      this.brandList = this.brandList.filter(e => e.id !== brand.id);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    querySearchAsync(queryString, cb) {
      this.queryData.name = queryString || "";
      getBrandsByName(this.queryData).then(response => {
        // let rows = response.rows;
        // let results = []; // [{ "value": "华为", "id": 2 }]
        // for (const index in rows) {
        //   let brand = rows[index]
        //
        //   let option = {};
        //   option.id = brand.id
        //   option.value = brand.name;
        //   results.push(option)
        // }

        let results = response.rows.map(item => {   // [{ "value": "华为", "id": 2 }] 要求要value方式渲染
          return {
            id: item.id,
            value: item.name
          }
        })
        cb(results);
      })
    },

    handleSelect(option) {
      const tag = {};
      tag.id = option.id;
      tag.name = option.value;

      if ( this.brandList.some(e => e.id === option.id) ){
        let name = this.queryString;
        this.$modal.msgWarning("品牌 [ " + name + " ] 已在待关联列表中");
        this.queryString = "";
        this.inputVisible = false;
        return;
      }

      this.brandList.push(tag);
      this.queryString = "";
      this.inputVisible = false;

    },

    handlingAssociatedBrands() {
      const body = {
        categoryId: this.categoryId,
        brandIds: this.brandList.map(item => item.id)
      };
      updateBrand(body).then(response => {
        this.$emit("brandAssociationUpdate")
        this.$modal.msgSuccess("修改成功");
        this.isBrandDialogVisible = false;
      })
    },

    onCloseBrandDialog() {
      this.brandList = [];
      this.queryString = "";
      this.inputVisible = false;
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
  margin-top: 10px;
}

.button-new-tag {
  margin-top: 10px;
  margin-left: 10px;
  height: 30px;
  line-height: 28px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-top: 10px;
  margin-left: 10px;
  vertical-align: bottom;
}

</style>
